package com.pda.yuanjing.pages.kcpd.scanf;

import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.pda.yuanjing.PDApp;
import com.pda.yuanjing.R;
import com.pda.yuanjing.beanin.AddCBillBeanIn;
import com.pda.yuanjing.beanout.JDBeanDNewOut;
import com.pda.yuanjing.boardcast.CustomReceiver;
import com.pda.yuanjing.boardcast.ScannerInterface;
import com.pda.yuanjing.dialog.error.ErrorDialog;
import com.pda.yuanjing.message.MessageBus;
import com.pda.yuanjing.thread.CodeBeans;
import com.public_module.basemvp.activity.BaseActivity;
import com.public_module.dialogs.ChooseDialog;
import com.public_module.tools.DensityUtil;
import com.public_module.tools.SharedPreferencesManger;
import com.public_module.tools.StringProcess;
import com.public_module.tools.VoiceUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PDScanfActivity extends BaseActivity<ScanfModel, ScanfView, ScanfPresent> implements ScanfView {
    @BindView(R.id.iv_title_left)
    ImageView ivTitleLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rltitle)
    RelativeLayout rltitle;
    @BindView(R.id.tvbill)
    TextView tvbill;
    @BindView(R.id.tvname)
    TextView tvname;
    @BindView(R.id.login_id)
    EditText loginId;
    @BindView(R.id.logine)
    Button logine;
    @BindView(R.id.sws)
    Switch sws;
    @BindView(R.id.ivd)
    ImageView ivd;
    @BindView(R.id.listview)
    ListView listview;
    @BindView(R.id.tvres)
    TextView tvres;
    @BindView(R.id.tvs)
    TextView tvs;
    @BindView(R.id.tv0)
    TextView tv0;
    @BindView(R.id.tvwait)
    TextView tvwait;
    @BindView(R.id.tvr)
    TextView tvr;
    @BindView(R.id.tvsn)
    TextView tvsn;

    private String TAG = "BMScanfActivity";
    int scanfState = 0;
    boolean flag = true;
    ScannerInterface scanner;
    CustomReceiver customReceiver = null;
    VoiceUtils voiceUtils;
    List<Integer> codeNums = new ArrayList<>();
    int pIndex = -1;
    CodeBeans codeBeans = new CodeBeans();
    Thread upThread = null;
    boolean exit = false;
    CodeBMAdapter codeBMAdapter;
    JDBeanDNewOut dataBean = null;
    List<JDBeanDNewOut.DataBean> plist = new ArrayList<>();
    AddCBillBeanIn addCBillBeanIn = new AddCBillBeanIn();

    protected void initdata() {
        dataBean = (JDBeanDNewOut) getIntent().getSerializableExtra(PDApp.process);
        tvTitle.setText(dataBean.getJieDianName() + " " + SharedPreferencesManger.getRealName());
        tvbill.setText(dataBean.getBatch());
        tvname.setText(dataBean.getStoreNameIn());
        tvr.setText("确认盘点");
        chooseDialog = new ChooseDialog(this, "是否确认盘点", R.style.CommentDialog, new ChooseDialog.PriorityListener() {
            @Override
            public void setActivityText() {
                presenter.confirePD(addCBillBeanIn);
            }
        });
        WindowManager.LayoutParams lp = chooseDialog.getWindow().getAttributes();
        lp.gravity = Gravity.CENTER;

        scanner = new ScannerInterface(this);
        scanner.setOutputMode(1);
        customReceiver = new CustomReceiver(
                new CustomReceiver.PListener1() {
                    @Override
                    public void setData(CustomReceiver.Dataa dataa) {
                        tvs.setText(dataa.getStr());
                        scanfState = dataa.getType();
                        if (scanfState == -1) {
                            tvs.setBackgroundResource(R.color.smalltext);
                        } else {
                            tvs.setBackgroundResource(R.color.green);
                        }
                    }
                },
                new CustomReceiver.PListener2() {
                    @Override
                    public void setText(String string) {
                        if (!PDApp.scanf) {
                            return;
                        }
                        if (scanfState == -1) {
                            showres("网络异常,请检查网络");
                            return;
                        }
                        String ss = StringProcess.codeMat(string);
                        CodeBeans.Code cbean = new CodeBeans.Code();
                        cbean.setStr(ss);
                        cbean.setFlag(flag);
                        codeBeans.addCode(cbean);
                        tvwait.setText(codeBeans.getCodes().size() + "");
                    }
                });
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(ScannerInterface.RES_ACTION);
        registerReceiver(customReceiver, filter);
        voiceUtils = new VoiceUtils(this);
        upThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!exit) {
                    if (codeBeans!=null && codeBeans.getCodes().size() > 0) {
                       try {
                           presenter.scanfBM(dataBean.getBatchID(), dataBean.getJieDianName(), "-1", codeBeans.getCodes().get(0).getStr(), "", codeBeans);
                       }catch (Exception e){
                           e.printStackTrace();
                       }
                    }
                }
            }
        });
        upThread.start();
        plist = dataBean.getData();
        codeBMAdapter = new CodeBMAdapter(this, plist);
        listview.setAdapter(codeBMAdapter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sp_scanf);
        ButterKnife.bind(this);
        initdata();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (customReceiver != null) {
            unregisterReceiver(customReceiver);
        }
        if (scanner != null) {
            scanner.setOutputMode(0);
        }
        EventBus.getDefault().unregister(this);
        exit = true;
        upThread = null;
    }

    @Override
    public ScanfModel createModel() {
        return new ScanfModelImpl(this);
    }

    @Override
    public ScanfView createView() {
        return this;
    }

    @Override
    public ScanfPresent createPresenter() {
        return new ScanfPresent();
    }


    @OnClick({R.id.iv_title_left, R.id.logine, R.id.ivd,R.id.tvr})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.tvr:
                addCBillBeanIn.setCid(SharedPreferencesManger.getCid());
                addCBillBeanIn.setAction("SY_ComfirePD");
                addCBillBeanIn.setUserID(SharedPreferencesManger.getUid());
                addCBillBeanIn.setStoreID(SharedPreferencesManger.getStoreID());
                addCBillBeanIn.setBatchID(dataBean.getBatchID());
                for (int i = 0; i < plist.size(); i++) {
                    if(plist.get(i).isCk()){
                        AddCBillBeanIn.DataBean dataBean = new AddCBillBeanIn.DataBean();
                        dataBean.setPlanNums(plist.get(i).getPlanNums());
                        dataBean.setProductID(plist.get(i).getProductID());
                        dataBean.setProductName(plist.get(i).getProductName());
                        addCBillBeanIn.getListProduct().add(dataBean);
                    }
                }
                if(addCBillBeanIn.getListProduct().size()==0){
                    showMsg("没有选择任何产品");
                    return;
                }else
                {
                    chooseDialog.show();
                }
                break;
            case R.id.ivd:
                if (flag) {
                    chooseDialog.show();
                } else {
                    flag = true;
                    ivd.setImageResource(R.mipmap.icon_nocheck);
                }
                break;
            case R.id.logine:
                if (scanfState == -1) {
                    showres("网络异常,请检查网络");
                    return;
                }
                CodeBeans.Code cbean = new CodeBeans.Code();
                cbean.setStr(loginId.getText().toString());
                cbean.setFlag(flag);
                codeBeans.addCode(cbean);
                tvwait.setText(codeBeans.getCodes().size() + "");
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    public void showres(String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                voiceUtils.voiceWarn();
                tvres.setText(str);
                loginId.setText("");
                tvwait.setText(codeBeans.getCodes().size() + "");
                if (PDApp.cidInfoBeanOut.getData()!=null && PDApp.cidInfoBeanOut.getData().isShowErrorDialog()) {
                    ErrorDialog errorDialog = new ErrorDialog(mContext, str, R.style.CommentDialog, new ErrorDialog.PriorityListener() {
                        @Override
                        public void setActivityText() {
                        }
                    });
                    WindowManager.LayoutParams lp = errorDialog.getWindow().getAttributes();
                    lp.gravity = Gravity.CENTER;
                    errorDialog.show();
                    Window window = errorDialog.getWindow();
                    window.setBackgroundDrawableResource(android.R.color.transparent);
                    WindowManager.LayoutParams attrs = window.getAttributes();
                    attrs.width = (int) DensityUtil.dp2px(PDScanfActivity.this, 300);
                    attrs.height = WindowManager.LayoutParams.WRAP_CONTENT;
                    errorDialog.getWindow().setAttributes(attrs);
                }
            }
        });
    }

    @Override
    public void showSuccessres(String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showMsg("盘点完成");
                finish();
            }
        });
    }

    @Override
    public void showSuccessres(List<JDBeanDNewOut.DataBean> list) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvres.setText("数码处理完成");
                loginId.setText("");
                tvwait.setText(codeBeans.getCodes().size() + "");
                plist.clear();
                plist.addAll(list);
                codeBMAdapter.notifyDataSetChanged();
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBaseMessageEvent(MessageBus messageBus) {
//        for (int i = 0; i < plist.size(); i++) {
//            plist.get(i).setCk(false);
//        }
//        if (messageBus.getValue() == 1) {
//            plist.get(messageBus.getIndex()).setCk(true);
//            billListID = plist.get(messageBus.getIndex()).getBillListID();
//            pIndex = messageBus.getIndex();
//        } else {
//            plist.get(messageBus.getIndex()).setCk(false);
//            billListID = "-1";
//            pIndex = -1;
//        }
//        codeBMAdapter.notifyDataSetChanged();
    }
}
